﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 中介者模式
{
    public class Example2
    {
        //首先，我们定义一个抽象中介者类，他包含一个抽象的发送消息方法
        public abstract class ChatRoom
        {
            public abstract void SendMessage(string message,User sender);
            public abstract void AddUser(User user);
            public abstract void RemoveUser(User user);

        }
        //然后，我们定义一个具体的中介者类，他实现了发送消息方法，并维护了一个用户列表
        public class ChatRoomImpl : ChatRoom
        {
            private List<User> users=new List<User> ();
            public override void SendMessage(string message, User sender)
            {
                foreach(var user in users)
                {
                    if (user != sender)
                    {
                        user.ReceiveMessage(message);
                    }
                }
            }
            public override void AddUser(User user)
            {
                users.Add(user);
            }
            public override void RemoveUser(User user)
            {
                users.Remove(user);
            }

        }
        //接下来，我们定义一个抽象用户类，他包含一个发送消息方法和一个接受消息方法
        public abstract class User
        {
            protected ChatRoom chatRoom;
            public User(ChatRoom chatRoom)
            {
                this.chatRoom = chatRoom;
            }
            public abstract void SendMessage(string message);
            public abstract void ReceiveMessage(string message);
        }
        //最后，我们定义具体的用户类，他实现了发送消息和接收消息方法
        public class ConcreteUser : User
        {
            private string name;

            public ConcreteUser(string name,ChatRoom chatRoom) : base(chatRoom)
            {
                this.name = name;
            }
            public override void SendMessage(string message)
            {
                chatRoom.SendMessage(message,this);
            }
            public override void ReceiveMessage(string message)
            {
                Console.WriteLine("{0}Received message:{1}",name,message);
            }
        }
    }
}
